package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.MenuDao;
import com.itheima.dao.PermissionDao;
import com.itheima.dao.RoleDao;
import com.itheima.dao.UserDao;
import com.itheima.pojo.Menu;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.apache.xmlbeans.impl.jam.mutable.MElement;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service(interfaceClass = UserService.class)
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private RoleDao roleDao;

    @Autowired
    private PermissionDao permissionDao;

    @Autowired
    private MenuDao menuDao;

    @Override
    public User findByUserName(String username) {
        //根据用户名获取到对应的用户数据
        User user = userDao.findByUserName(username);
        //根据用户的id获取到对应的role信息
        Set<Role> roles = roleDao.findByUserId(user.getId());
        if (roles != null){
            for (Role role : roles) {
                //根据角色id获取到对应的权限信息
                Set<Permission> permissions = permissionDao.findByRoleId(role.getId());
                role.setPermissions(permissions);

                //根据角色id获取到对应的菜单数据
                LinkedHashSet<Menu> menus = menuDao.findMenuByRoleId(role.getId());
                for (Menu menu : menus) {
                    Integer menuId = menu.getId();
                    Integer roleId = role.getId();

                    Map map = new HashMap();
                    map.put("roleId",roleId);
                    map.put("menuId",menuId);

                    //根据menuId获取到对应子菜单信息
                    List<Menu> childrenMenus = menuDao.findChildrenMenuByMenuId(map);
                    menu.setChildren(childrenMenus);
                }
                role.setMenus(menus);
            }
        }
        user.setRoles(roles);
        return user;
    }
}
